<?php

namespace app\common\library;

use think\Cache;

/**
 * 微信小程序类
 */
class Wxapp
{

    protected  $url= "https://api.weixin.qq.com";

    protected $app_id;

    protected $app_secret;

    public function __construct()
    {
        $cfg = config('site');
        $this->app_id     = $cfg["app_id"];
        $this->app_secret = $cfg["app_secret"];
    }

    /**
     * 调用凭据
     * @param $uid
     * @return mixed
     * @throws ApiException
     */
    private function getAccessToken($uid)
    {
        $token_key = "access-token".$uid;
        $access_token = Cache::get($token_key);
        if(!$access_token){
            $res = $this->http_request($this->url."/cgi-bin/stable_token",[
                "grant_type"    => "client_credential",
                "appid"         => $this->app_id,
                "secret"        => $this->app_secret,
            ],"post");
            if(isset($res["errcode"]) && !empty($res["errcode"])){
                throw new ApiException(sprintf("获取小程序token失败:%s",$res["errmsg"]));
            }
            $access_token = $res["access_token"];
            Cache::set($token_key,$access_token,7000);
        }

        return $access_token;
    }

    /**
     * 授权登录
     * @param $code
     * @return mixed
     * @throws ApiException
     */
    public function AuthLogin($code)
    {
        $res = $this->http_request($this->url."/sns/jscode2session",[
            "js_code"       => $code,
            "grant_type"    => "authorization_code",
            "appid"         => $this->app_id,
            "secret"        => $this->app_secret,
        ]);
        if(isset($res["errcode"]) && !empty($res["errcode"])){
            throw new ApiException(sprintf("小程序登录失败:%s",$res["errmsg"]));
        }
        return $res;
    }

    /**
     * 手机号授权
     * @param $uid
     * @param $code
     * @return mixed
     * @throws ApiException
     */
    public function AuthMobile($uid,$code)
    {
        $access_token = $this->getAccessToken($uid);
        $res = $this->http_request($this->url."/wxa/business/getuserphonenumber?access_token=".$access_token,[
            "code" => $code
        ],"post");
        if(isset($res["errcode"]) && !empty($res["errcode"])){
            throw new ApiException(sprintf("获取手机号失败:%s",$res["errmsg"]));
        }
        return $res["phone_info"];
    }

    protected function http_request($url,$params,$method="get")
    {
        if($method == "get"){
            $url = $url."?".http_build_query($params);
        }
        $curl = curl_init();
        curl_setopt($curl,CURLOPT_URL,$url);
        curl_setopt($curl,CURLOPT_HEADER,false);
        curl_setopt($curl,CURLOPT_HTTPHEADER,[
            "Content-Type:application/json",

        ]);
        curl_setopt($curl,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
        if($method == "post"){
            curl_setopt($curl,CURLOPT_POST,1);
            curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode($params));
        }
        $data = curl_exec($curl);
        curl_close($curl);
        return json_decode($data,true);
    }
}